import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.*;
import org.apache.hadoop.mapreduce.lib.output.*;
import org.apache.hadoop.util.*;

public class MergeRating extends Configured implements Tool 
{
	
	public static class Map extends
			Mapper<LongWritable, Text, LongWritable, FloatWritable> {

		public void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			StringTokenizer tokenizer = new StringTokenizer(line);
			Long objID = Long.parseLong(tokenizer.nextToken());
			Float rating = Float.parseFloat(tokenizer.nextToken());
			context.write(new LongWritable(objID), new FloatWritable(rating));
		}
	}

	public static class Reduce extends
			Reducer<LongWritable, FloatWritable, LongWritable, Text> {
		public void reduce(LongWritable key, Iterable<FloatWritable> values,
				Context context) throws IOException, InterruptedException {
			String sum = new String("");
			String carry = new String("");
			int count = 0;
			for (FloatWritable val : values) {
				Float v = val.get();
				if (v < 0) {
					sum += String.valueOf(Math.abs(v));
					sum += " ";	
				}
				else
					carry = String.valueOf(v);	
				count++;
			}
			if (count == 2) {
				sum += carry;
				context.write(key, new Text(sum));
			}
		}
	}

	public int run(String[] args) throws Exception {
		/* 
		 * Calculate ratings per article
		 */
		Job job = new Job(getConf());
		job.setJarByClass(MergeRating.class);
		job.setJobName("MergeRatings");

		job.setOutputKeyClass(LongWritable.class);
		job.setOutputValueClass(FloatWritable.class);

		job.setMapperClass(Map.class);
		job.setReducerClass(Reduce.class);

		job.setInputFormatClass(TextInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);

		FileInputFormat.setInputPaths(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		boolean success = job.waitForCompletion(true);
		return success ? 0 : 1;
	}

	 
	 public static void main(String[] args) throws Exception {
		int ret = ToolRunner.run(new MergeRating(), args);
		System.exit(ret);
	}

}
